package cn.gary.oaserver.controller;


import cn.gary.oaserver.config.utils.ConstansOA;
import cn.gary.oaserver.entity.TAdmin;
import cn.gary.oaserver.params.PageParams;
import cn.gary.oaserver.params.Result;
import cn.gary.oaserver.service.ITAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gary
 * @since 2024-03-15
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "操作员控制器")
public class TAdminController {

    @Autowired
    ITAdminService adminService;

    @Autowired
    PasswordEncoder passwordEncoder;

//    @PreAuthorize("hasAuthority('/admin/listAdmin?**')")
    @ApiOperation("根据条件查看操作员列表")
    @GetMapping("/listAdmin")
    public Result list(PageParams pageParams, String query) {
        System.out.println (pageParams );
        return Result.success ( "查询的操作员列表", adminService.getAdminListByQuery ( pageParams, query ) );
    }

    @PreAuthorize("hasAuthority('/admin/delAdmin/**')")
    @GetMapping("/delAdmin/{id}")
    @ApiOperation("根据Id删除操作员")
    public Result del(@PathVariable Integer id) {
        try {
            if (adminService.removeById ( id )) {
                return Result.success ( "删除成功", ConstansOA.STATE_SUCCESSFUL );
            } else {
                return Result.error ( "删除失败", ConstansOA.STATE_FAILURE );
            }
        } catch (Exception exception) {
            return Result.error ( "删除该用户需要先把权限删除", ConstansOA.STATE_FAILURE );
        }
    }

    @PreAuthorize ( "hasAuthority('/admin/getAdminById/**')" )
    @GetMapping("/getAdminById/{id}")
    @ApiOperation("根据Id查找操作员")
    public Result getAdminById(@PathVariable Integer id) {
        return Result.success ( "查找操作员", adminService.getById ( id ) );
    }

    @PreAuthorize("hasAuthority('/admin/saveAdmin')")
    @PostMapping("/saveAdmin")
    @ApiOperation("保存操作员（删除/修改）")
    public Result save(@RequestBody TAdmin admin) {
        String opr = "修改操作员";
        if (admin.getId ( ) == null) {
            opr = "新增操作员";
            admin.setPassword ( passwordEncoder.encode ( admin.getPassword () ) );
        }else {
            admin.setPassword ( null );
        }
        System.out.println ("admin:"+admin );
        return adminService.saveOrUpdate ( admin ) ? Result.success ( opr + "成功" ) : Result.success ( opr + "失败" );
    }


}
